package com.chinasoft.maysham.manager.service.config;

import com.chinasoft.maysham.manager.exception.BizException;
import com.chinasoft.maysham.manager.model.ClusterConfig;
import com.chinasoft.maysham.manager.model.Project;
import com.chinasoft.maysham.manager.model.ProjectConfig;
import com.chinasoft.maysham.manager.repo.config.ProjectConfigRepo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

@Service
public class ProjectConfigServiceImpl implements ProjectConfigService{

    @Resource
    private ProjectConfigRepo projectConfigRepo;

    @Override
    public ProjectConfig queryConfig(String projectId) {
        return projectConfigRepo.findByProjectId(projectId);
    }

    @Override
    public void init(Project project) {
        ProjectConfig config = new ProjectConfig();
        config.setProjectId(project.getId());
        ClusterConfig clusterConfig = new ClusterConfig();
        clusterConfig.setDockerBasePath("");
        config.setClusterConfig(clusterConfig);
        projectConfigRepo.save(config);
    }

    @Override
    public ProjectConfig updateConfig(String projectId, ProjectConfig config) {
        ProjectConfig projectConfig = projectConfigRepo.findByProjectId(projectId);
        if (projectConfig == null) {
            throw new BizException("invalid param");
        }
        if (config.getClusterConfig()!=null && !StringUtils.isEmpty(config.getClusterConfig().getDockerBasePath())) {
            projectConfig.getClusterConfig().setDockerBasePath(config.getClusterConfig().getDockerBasePath());
        }
        return projectConfigRepo.save(projectConfig);
    }
}
